<!-- canvas -->
<template>
  <div class="canvas-container">
    <canvas
      id="draw"
      v-if="!clearCanvas"
      @mousedown="mousedownHandler"
      @mousemove="mousemoveHandler"
      @mouseup="mouseupHandler"
    >浏览器不支持canvas</canvas>

    <div class="btn-group">
      <button class="btn" @click="saveHandler">保存</button>
      <button class="btn" @click="cancelHandler">清空</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'test4-canvas',
  data() {
    return {
      control: false,
      ctx: null,
      canvas: null,
      canvasWidth: 414,
      canvasHeight: 706,
      clearCanvas: false,
    }
  },
  methods: {
    initCanvas() {
      const index = setInterval(() => {
        const canvas = document.getElementById('draw')
        if (!!canvas) {
          clearInterval(index)
          const ctx = canvas.getContext('2d')
          canvas.width = this.canvasWidth
          canvas.height = this.canvasHeight
          // 设置或返回两条线相交时，所创建的拐角类型
          ctx.lineJoin = 'round'
          // 设置或返回线条的结束端点样式
          ctx.lineCap = 'round'
          // 画笔颜色
          ctx.strokeStyle = '#000'
          //  画笔粗细
          ctx.lineWidth = 5
          this.ctx = ctx
          this.canvas = canvas
        }
      }, 100)
    },
    mousedownHandler(e) {
      this.control = true
      let mouseX = e.offsetX
      let mouseY = e.offsetY
      this.ctx.moveTo(mouseX, mouseY)
    },
    mouseupHandler() {
      this.control = false
    },
    mousemoveHandler(e) {
      if (this.control) {
        let mouseX = e.offsetX
        let mouseY = e.offsetY
        // 终止位置
        this.ctx.lineTo(mouseX, mouseY)
        // 结束图形
        this.ctx.stroke()
      }
    },
    saveHandler() {
      let imageData = this.canvas.toDataURL({
        format: 'png',
        quality: 1,
        width: this.canvasWidth,
        height: this.canvasHeight,
      })
      this.$emit('save', imageData)
    },
    cancelHandler() {
      this.clearCanvas = true
      setTimeout(() => {
        this.clearCanvas = false
        this.initCanvas()
      }, 100)
    },
  },
  mounted() {
    this.initCanvas()
  },
}
</script>
<style  scoped>
.btn {
  width: 100px;
  height: 30px;
  margin: 10px 5px;
}
.canvas-container {
  border: 1px solid #42b983;
  width: 414px;
  height: 756px;
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
  align-content: center;
  position: relative;
}

.btn-group {
  width: 414px;
  height: 50px;
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
  align-content: center;
  position: absolute;
  bottom: 0;
  border-top: 1px solid #42b983;
}
</style>